package com.dz.util;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;

import java.util.Map;
import java.util.UUID;

//验证码工具类
public class CaptchaUtil {
    private static final ExpiryMap expiryMap = new ExpiryMap();
    private static final long EXPIRY_TIME = 1000 * 60 * 5;

    /*获取验证码*/
    public static Map getCaptcha() {
        //定义验证码的长度和高度
        LineCaptcha lineCaptcha = cn.hutool.captcha.CaptchaUtil.createLineCaptcha(200, 100, 4, 20);
        //图片:获取图片的base64编码
        String imageBase64 = Base64.encode(lineCaptcha.getImageBytes());
        //System.out.println(imageBase64);
        //验证码中的编号
        String code = lineCaptcha.getCode();
        //System.out.println("验证码中的编号：" + code);
        String key = UUID.randomUUID().toString();
        Map map = Map.of("key", key, "base", "data:image/png;base64," + imageBase64);
        expiryMap.put(key,code,EXPIRY_TIME);
        return map;
    }

    public static boolean checkCaptcha(String key, String code) {
        // 检查参数是否为null
        if (key == null || code == null) {
            //System.out.println("验证码参数为null: key=" + key + ", code=" + code);
            return false;
        }

        // 从expiryMap中获取验证码
        String captchaCode = (String) expiryMap.get(key);

        // 检查验证码是否存在且不为null
        if (captchaCode == null) {
            //System.out.println("验证码不存在或已过期: key=" + key);
            return false;
        }

        // 比较验证码（忽略大小写）
        boolean result = code.equalsIgnoreCase(captchaCode);
        //System.out.println("验证码验证结果: 输入=" + code + ", 正确=" + captchaCode + ", 结果=" + result);
        expiryMap.remove(key);
        return result;
    }

}
